package com.anXin.article.service.impl;



import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.anXin.apis.user.IUserClient;
import com.anXin.article.mapper.ArticlePublishMapper;
import com.anXin.article.service.*;


import com.anXin.common.constants.ArticleMessageConstants;
import com.anXin.model.article.dtos.ArticlePublishDto;
import com.anXin.model.article.pojos.Article;

import com.anXin.model.article.pojos.ArticleChannel;
import com.anXin.model.common.dtos.ResponseResult;
import com.anXin.model.common.enums.AppHttpCodeEnum;

import com.anXin.model.user.dtos.UserInfoDto;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import utils.thread.AppThreadLocalUtil;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;


@Service
@Slf4j
@Transactional
public class ArticlePublishServiceImpl extends ServiceImpl<ArticlePublishMapper, Article> implements ArticlePublishService {




    @Autowired
    private FileStorageService fileStorageService;


    @Resource
    private ArticleChannelService articleChannelService;

    @Resource
    private ArticleTaskService articleTaskService;

    @Lazy
    @Resource
    private ArticleService articleService;



    /**
     * 图片上传
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {

        //1.检查参数
        if(multipartFile == null || multipartFile.getSize() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.上传图片到minIO中
        String fileName = UUID.randomUUID().toString().replace("-", "");
        //aa.jpg
        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileId = null;
        try {
            fileId = fileStorageService.uploadImgFile("", fileName + postfix, multipartFile.getInputStream());
            log.info("上传图片到MinIO中，fileId:{}",fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl-上传文件失败");
        }

        //3.保存到数据库中
        //4.返回结果

        return ResponseResult.okResult(fileId);
    }

    /**
     * 发布修改文章或保存为草稿
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(ArticlePublishDto dto) {

        //0.条件判断
        if(dto == null || dto.getContent() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //1.保存或修改文章

        Article article = new Article();
        //属性拷贝 属性名词和类型相同才能拷贝
        BeanUtils.copyProperties(dto,article);//拷贝到文章表


        //封面图片  list---> string
        if(dto.getImages() != null && dto.getImages().size()> 0){
            //[1dddfsd.jpg,sdlfjldk.jpg]-->   1dddfsd.jpg,sdlfjldk.jpg
            String imageStr = StringUtils.join(dto.getImages(), ",");
            article.setImages(imageStr);
        }
        saveOrUpdateWmNews(article);
        //2.判断是否为草稿  如果为草稿结束当前方法
        if(dto.getStatus().equals(Article.Status.NORMAL.getCode())){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        if (!dto.getImages().isEmpty()){
            ResponseResult responseResult = articleService.saveArticle(article);
            if (!responseResult.getCode().equals(200)){
                throw new RuntimeException("AutoScanServiceImpl-文章审核保存APP端失败!");
            }
        }
        articleTaskService.addToTask(article.getId(), article.getPublishTime());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    @Resource
    private KafkaTemplate<String,String> kafkaTemplate;
    @Override
    public ResponseResult downOrUp(ArticlePublishDto dto) {
        //检查参数
        if (dto.getId()==null){
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询文章
        Article article = getById(dto.getId());
        if (article==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //判断文章是否已发布
        if (!article.getStatus().equals(Article.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }

        //修改文章enable
        if (dto.getEnable()!=null&&dto.getEnable()>-1&&dto.getEnable()<2){
            update(Wrappers.<Article>lambdaUpdate().set(Article::getEnable,dto.getEnable()).eq(Article::getId,article.getId()));
            //发送消息，通知article修改文章配置
            if (article.getId()!=null) {
                Map<String,Object> map=new HashMap<>();
                map.put("articleId",article.getId());
                map.put("enable",dto.getEnable());
                kafkaTemplate.send(ArticleMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Resource
    private IUserClient userClient;
    /**
     * 保存或修改文章
     * @param article
     */
    private void saveOrUpdateWmNews(Article article) {
        //补全属性
        Long userId = AppThreadLocalUtil.getUser().getId();

//        article.setAuthorName(user.getName());
        article.setAuthorId(userId);
        LinkedHashMap<String, Object> data = (LinkedHashMap<String, Object>) userClient.information(userId).getData();
        UserInfoDto userInfoDto = JSONUtil.toBean(JSONUtil.toJsonStr(data), UserInfoDto.class);
        article.setAuthorName(userInfoDto.getName());
        ArticleChannel channel = articleChannelService.query().eq("id", article.getChannelId()).one();
        article.setChannelName(channel.getChannelName());
        article.setCreatedTime(new Date());
        article.setPublishTime(new Date());
        article.setEnable((short)1);//默认上架
        if(article.getId() == null){
            //保存
            save(article);
        }

    }


}
